package com.baiyang.app.ui.bookCity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.baiyang.app.HomeActivity;
import com.baiyang.app.R;
import com.baiyang.app.tool.LogUtils;
import com.baiyang.app.tool.net.SendMsgUtil;
import com.baiyang.app.tool.net.Urls;
import com.baiyang.app.ui.read.ReadPageActivity;

import org.jetbrains.annotations.NotNull;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

public class BookCityAdapter extends RecyclerView.Adapter<BookCityAdapter.ViewHolder>  {
    private List<JSONObject> list;
    private Context context;

    public BookCityAdapter(Context context,List<JSONObject> list) {
        this.list = list;
        this.context = context;
    }
    public static final int ARTICLE = 0x11;
    public static final int FEATURED = 0x12;
    public static final int LEADERBOARD = 0x13;
    public static final int LABEL = 0x14;

    /**
     * 返回视图类型
     * @param position
     * @return
     */
    @Override
    public int getItemViewType(int position) {
        JSONObject object = list.get(position);
        Integer viewType = object.getInteger("viewType");
        return viewType==null?0:viewType;
    }

    public JSONObject getItem(int position) {
        return list.get(position);
    }

    /**
     * 根据视图类型创建ViewHolder
     * @param parent
     * @param viewType
     * @return
     */
    @NonNull
    @NotNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        switch (viewType){
            case ARTICLE:
            {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_article,parent,false);
                ViewHolder holder = new ViewHolder(view);
                return holder;
            }
            case FEATURED:
            {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_featured,parent,false);
                ViewHolder holder = new ViewHolder(view);
                return holder;
            }
            case LEADERBOARD:
            {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_leaderboard,parent,false);
                ViewHolder holder = new ViewHolder(view);
                return holder;
            }
            case LABEL:
            {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_label,parent,false);
                ViewHolder holder = new ViewHolder(view);
                return holder;
            }
        }
        return null;
    }

    /**
     * 实现视图view赋值
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(@NonNull @NotNull BookCityAdapter.ViewHolder holder, int position) {
        JSONObject object = getItem(position);
        int viewType = getItemViewType(position);
        switch (viewType){
            case ARTICLE:
            {
                createArticle(holder,object);
                break;
            }
            case FEATURED:
            {
                createFeatured(holder,object);
                break;
            }
            case LEADERBOARD:
            {
                createLeaderboard(holder,object);
                break;
            }
            case LABEL:
            {
                createLabel(holder,object);
                break;
            }
        }
    }

    private void createLabel(ViewHolder holder, JSONObject object) {
        String label = object.getString("label");
        holder.setText(R.id.label,label);
    }

    private void createLeaderboard(ViewHolder holder, JSONObject object) {
        JSONObject left = object.getJSONObject("left");
        JSONObject right = object.getJSONObject("right");
        String pic,articleName,readerNum,ranking;
        if(left != null){
            pic = left.getString("pic");
            holder.setPic(R.id.left_pic,pic);
            articleName = left.getString("articleName");
            holder.setText(R.id.left_name,articleName);
            readerNum = left.getString("readerNum");
            holder.setText(R.id.left_reader_num,readerNum);
            ranking = left.getString("ranking");
            holder.setText(R.id.left_ranking,"TOP" + ranking);
            holder.setmOnItemClickListener(e->{
                Intent intent = new Intent();
                intent.putExtra("articleId",left.getString("id"));
                intent.setClass(context, ReadPageActivity.class);
                context.startActivity(intent);
                ((HomeActivity)context).overridePendingTransition(R.anim.left_in,R.anim.right_out);
            });
        }
        if(right != null){
            pic = right.getString("pic");
            holder.setPic(R.id.right_pic,pic);
            articleName = right.getString("articleName");
            holder.setText(R.id.right_name,articleName);
            readerNum = right.getString("readerNum");
            holder.setText(R.id.right_reader_num,readerNum);
            ranking = right.getString("ranking");
            holder.setText(R.id.right_ranking,"TOP" + ranking);
            holder.setmOnItemClickListener(e->{
                Intent intent = new Intent();
                intent.putExtra("articleId",right.getString("id"));
                intent.setClass(context, ReadPageActivity.class);
                context.startActivity(intent);
                ((HomeActivity)context).overridePendingTransition(R.anim.left_in,R.anim.right_out);
            });
        }
    }


    private void createFeatured(ViewHolder holder, JSONObject object) {
        String pic = object.getString("pic");
        holder.setPic(R.id.article_pic,pic);
        String articleName = object.getString("articleName");
        holder.setText(R.id.name,articleName);
        String introduction = object.getString("introduction");
        holder.setText(R.id.introduction,introduction);
        String articleType = object.getString("articleType");
        holder.setText(R.id.article_type,articleType);
        String readerNum = object.getString("readerNun");
        holder.setText(R.id.reader_num,readerNum);
        holder.setmOnItemClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("articleId",object.getString("id"));
                intent.setClass(context, ReadPageActivity.class);
                context.startActivity(intent);
                ((HomeActivity)context).overridePendingTransition(R.anim.left_in,R.anim.right_out);
            }
        });
    }

    private void createArticle(ViewHolder holder, JSONObject object) {
        String pic = object.getString("pic");
        holder.setPic(R.id.article_pic,pic);
        String articleName = object.getString("articleName");
        holder.setText(R.id.name,articleName);
        String introduction = object.getString("introduction");
        holder.setText(R.id.introduction,introduction);
        String articleType = object.getString("articleType");
        holder.setText(R.id.article_type,articleType);
        String readerNum = object.getString("readerNum");
        holder.setText(R.id.reader_num,readerNum);
        holder.setmOnItemClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("articleId",object.getString("id"));
                intent.setClass(context, ReadPageActivity.class);
                context.startActivity(intent);
                ((HomeActivity)context).overridePendingTransition(R.anim.left_in,R.anim.right_out);
            }
        });
    }


    @Override
    public int getItemCount() {
        return list==null?0:list.size();
    }

    public void add(JSONObject data) {
        if (list == null) {
            list = new ArrayList<JSONObject>();
        }
        list.add(data);
        notifyDataSetChanged();
    }
    public void addAll(List<JSONObject> list) {
        if (this.list == null) {
            this.list = new ArrayList<JSONObject>();
        }
        this.list.addAll(list);
        notifyDataSetChanged();
    }
    public void add(int position, JSONObject data) {
        if (list == null) {
            list = new ArrayList<JSONObject>();
        }
        list.add(position, data);
        notifyDataSetChanged();
    }
    public void remove(JSONObject data) {
        if (list != null) {
            list.remove(data);
        }
        notifyDataSetChanged();
    }
    public void remove(int position) {
        if (list != null) {
            list.remove(position);
        }
        notifyDataSetChanged();
    }
    public void clear() {
        if (list != null) {
            list.clear();
        }
        notifyDataSetChanged();
    }


    public static class ViewHolder extends RecyclerView.ViewHolder {
        private SparseArray<View> mViews;
        private View item;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            mViews = new SparseArray<View>();
            item = itemView;
        }

        public void setmOnItemClickListener(View.OnClickListener onClickListener){
            item.setOnClickListener(onClickListener);
        }
        public void setLongClick(View.OnLongClickListener longClick){
            item.setLongClickable(true);
            item.setOnLongClickListener(longClick);
        }
        public ViewHolder setText(int id, CharSequence text) {
            View view = getView(id);
            if (view instanceof TextView) {
                ((TextView) view).setText(text);
            }
            return this;
        }
        public ViewHolder setPic(int id, Bitmap bitmap){
            View view = getView(id);
            if (view instanceof ImageView) {
                ((ImageView) view).setImageBitmap(bitmap);
            }
            return this;
        }
        public ViewHolder setPic(int id, Uri uri){
            View view = getView(id);
            if (view instanceof ImageView) {
                ((ImageView) view).setImageURI(uri);
            }
            return this;
        }

        /**
         * 从网络上获取图片
         * @param id
         * @param url
         * @return
         */
        public ViewHolder setPic(int id,String url){
            View view = getView(id);
            if (view instanceof ImageView) {
                new SendMsgUtil() {
                    @Override
                    public void deal(Call call, Response response) throws IOException {
                        if(response.isSuccessful()){
                            byte[] result = response.body().bytes();
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inSampleSize = 4;
                            ByteArrayInputStream in = new ByteArrayInputStream(result);
                            Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
                            view.post(new Runnable() {
                                @Override
                                public void run() {
                                    ((ImageView) view).setImageBitmap(bitmap);
                                }
                            });
                        }
                    }
                    @Override
                    public void dealFailure(Call call, IOException e) throws IOException {
                        LogUtils.i("getPic","IOException:" + e.getLocalizedMessage());
                    }
                }.sendGet(Urls.IMAGE + url);
            }
            return this;
        }
        public ViewHolder setColor(int id, int color){
            View view = getView(id);
            if (view instanceof ImageView) {
                ((TextView) view).setTextColor(color);
            }
            return this;
        }

        public <T extends View> T getView(int id) {
            T t = (T) mViews.get(id);
            if (t == null) {
                t = (T) item.findViewById(id);
                mViews.put(id, t);
            }
            return t;
        }
    }
}
